/* 定位相关服务 */
import {
  Action,
  getModule,
  Module,
  Mutation,
  VuexModule
} from 'vuex-module-decorators'

import { getLocationInfo } from '@/api/sys/location'
import { LocationResult } from '@/api/sys/model/locationModel'
import { hasCacheB } from '@/store/plugins'
import { toPromise } from '@/utils'

import store from '../instance'

interface LocationState {
  /* 当前定位信息 */
  readonly currentLocation: MaybeNull<LocationResult>

  /* 定位历史信息 */
  readonly historyList: LocationResult[]
}

@Module({
  namespaced: true,
  name: 'location',
  dynamic: true,
  store,
  preserveState: hasCacheB('location')
})
export default class Location extends VuexModule implements LocationState {
  private _currentLocation: MaybeNull<LocationResult> = null

  private _historyList: LocationResult[] = []

  private _lastUpdateTime = 0

  get currentLocation() {
    return this._currentLocation
  }

  get historyList() {
    return this._historyList
  }

  @Mutation
  updateLocation(val: LocationResult) {
    // this._currentLocation && this._historyList.push(this._currentLocation)
    this._currentLocation = val
    // if (this._historyList.length > 60) {
    //   this._historyList.splice(60)
    // }
  }

  @Mutation
  setLastUpdateTime(): void {
    this._lastUpdateTime = Date.now()
  }

  @Mutation
  $resetState() {
    this._currentLocation = null
    this._historyList = []
    this._lastUpdateTime = 0
  }

  @Action
  async getLocation() {
    if (Date.now() - this._lastUpdateTime > 30 * 1000) {
      return this.requestLocationInfo()
    }
    return this.currentLocation as LocationResult
  }

  @Action
  async requestLocationInfo() {
    const { latitude, longitude } = await toPromise(wx.getLocation, {
      type: 'gcj02',
      isHighAccuracy: false
    })
    const result = await getLocationInfo(latitude, longitude)
    this.updateLocation(result)
    this.setLastUpdateTime()
    return result
  }
}

export const locationStore = getModule<Location>(Location)
